package com.wm.task.common.util;

import java.io.*;

public class FileHelper {
    public static File getFile(String path) {
        String result = Const.ROOT + path;
        //System.out.println(result);
        File file = new File(result);
        File dir = file.getParentFile();
        if (!dir.exists() || !dir.isDirectory()) {
            dir.mkdirs();
        }
        //System.out.println(file.getAbsoluteFile());
        return file;
    }

    public static void writeFile(File file, String data, boolean append) {
        try (FileWriter fileWriter = new FileWriter(file, append)) {
            fileWriter.write(data);
        } catch (Exception e) {

        }
    }

    public static void writeFile(String path, String data, boolean append) {
        writeFile(getFile(path), data, append);
    }

    public static String readFile(File file) {
        String result = "";
        try (FileReader fileReader = new FileReader(file)) {
            while (true) {
                int code = fileReader.read();
                if (code == -1) break;
                result += (char) code;
            }
        } catch (Exception e) {

        }
        return result;
    }

    public static String readFile(String path) {
        return readFile(getFile(path));
    }

    public static void writeObjectFile(File file, Object data) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
            oos.writeObject(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//    public static void writeObjectFile(File file, Object data,boolean append) {
//        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file,append))) {
//            oos.writeObject(data);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public static Object readObjectFile(File file) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            return ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
